__file__ = 'A15.py'
__author__ = 'Jerry Liu'
__date__ = '2016-04-14'

"""
    问题：纯文本文件 city.txt为城市信息, 里面的内容（包括花括号）如下所示：
        {
            "1" : "上海",
            "2" : "北京",
            "3" : "成都"
        }
        请将上述内容写到 city.xls 文件中，如下图所示：
"""

from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter

def getdata():
    # 读取文档数据
    f = open('d://city.txt').read()
    # 转换为dict类型
    d = eval(f)
    savefile(d)

def savefile(d):
    # 新建excel
    wb = Workbook()
    ew = ExcelWriter(workbook=wb)
    filepath = 'd://city.xlsx'
    # 第一个sheet
    ws = wb.worksheets[0]
    row = 1
    for k, v in d.items():
        print('%s:%s' % (k, v))
        ws.cell(row=row, column=1, value=k)
        ws.cell(row=row, column=2, value=v)
        row += 1

    # 保存
    ew.save(filepath)
    print('保存成功')

if __name__ == '__main__':
    getdata()